<?php


namespace Anchu\Restful\Runner\Decorates;


use Carbon\Carbon;

class Filter
{
    // 查询条件
    public array $where = [];
    // 查询字段
    public array $field = ['*'];
    // 附属表内容
    public array $with = [];
    // 排序
    public array $orderBy = [];
    // 分页的时候使用，表示获取第几页的数据
    public int $currentPage = 1;
    // 分页的时候使用，表示一页中有多少条数据
    public int $perPage = 15;

    /**
     * 辅助变量，用于需要获取等值搜索条件进行逻辑处理的地方
     * 举例1：
     * $filter = ['key1' => 'value1']
     * =>
     * $columns = ['key1' => 'value1']
     *
     * 举例2：
     * $filter = [['key1', 'value1'], ['key2', '=', 'value2']]
     * =>
     * $columns = ['key1' => 'value1', 'key2' => 'value2']
     *
     */
    public array $columns = [];


    public function __construct()
    {
        $this->getWhere();
        $this->getField();
        $this->getWith();
        $this->getOrderBy();
        $this->getPerPage();
        $this->getCurrentPage();
    }

    private function getWhere()
    {
        $where = [];
        $columns = [];
        if (request()->query('filter')) {
            $filters = request()->query('filter');
            $filters = is_array($filters) ? $filters : json_decode($filters, 1);
            if (is_array($filters)) {
                foreach ($filters as $name => $value) {
                    if (!is_numeric($name)) {
                        // $filter = ['title' => 'xxx']
                        $where[] = [$name, '=', $value];
                        $columns[$name] = $value;
                    } elseif (is_array($value) && count($value) == 2) {
                        // $filter = [['title' => 'xxx']]
                        $where[] = [$value[0], '=', $value[1]];
                        $columns[$value[0]] = $value[1];
                    } elseif (is_array($value) && count($value) == 3) {
                        // $filter = [['title' ,'like', 'xxx']]
                        if ($value[1] == 'like') {
                            $value[2] = '%' . $value[2] . '%';
                        }
                        // $filter = [['published_at' ,'<=', '2022-09-28']]
                        if ($value[1] == '<=' && strtotime($value[2]) !== false) {
                            $value[2] = Carbon::parse($value[2])->endOfDay()->toDateTimeString();
                        }
                        if ($value[1] == '=') {
                            $columns[$value[0]] = $value[1];
                        }
                        $where[] = $value;
                    }
                }
            }
        }
        $this->where = $where;
        $this->columns = $columns;
    }

    /**
     * 从参数中获取需要返回哪些字段
     */
    private function getField()
    {
        $field = json_decode(request()->query('field', '["*"]'), 1);
        $this->field = is_array($field) ? $field : ['*'];
    }

    /**
     * 获取子表的信息，子表中需要带有主表的主键字段，以及模型类中有belongTo()、hasMany()等支持
     * 传参举例：
     * with=['table1:column1,column2', 'table2:column1,column2']
     */
    private function getWith()
    {
        $with = json_decode(request()->query('with', '[]'), 1);
        $this->with = is_array($with) ? $with : [];
    }

    /**
     * 获取子表的信息，子表中需要带有主表的主键字段，以及模型类中有belongTo()、hasMany()等支持
     * 传参举例：
     * with=['table1:column1,column2', 'table2:column1,column2']
     */
    private function getOrderBy()
    {
        $orderBy = json_decode(request()->query('order_by', '{"id": "desc"}'), 1);
        $this->orderBy = is_array($orderBy) ? $orderBy : ['id' => 'desc'];
    }


    /**
     * 获取当前页是第几页
     */
    public function getCurrentPage()
    {
        $this->currentPage = intval(request()->query('page', 1));
    }

    /**
     * 获取当前页是第几页
     */
    public function getPerPage()
    {
        $this->perPage = intval(request()->query('per_page', 15));
    }
}
